// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const dayBill = "d_bill_day"
const billType = "s_bill_type"
const billTotal = "d_bill_total"
var wxContext = {};
// 云函数入口函数
exports.main = async (event, context) => {
	wxContext = cloud.getWXContext();
	let result = {
		a: false,
		b: {}
	};
	switch (event.funName) {
		case "addBill":
			result = await addBill(event);
			break;
		case "getBillType":
			result = await getBillType(event);
			break;
		case "addBillType":
			result = await addBillType(event);
			break;
		case "getBillList":
			result = await getBillList(event);
			break;
		case "getMonthTotal":
			result = await getMonthTotal(event);
			break;
		default:
			break;
	}
	return result;
}
// 获取记账项目
async function getBillType(event) {
	let result = {
		a: true,
		b: {}
	};
	result.b = await db.collection(billType)
		.field({
			name: true,
			pId: true,
			icon: true
		})
		.orderBy('o', 'desc')
		.get();
	return result;
}
// 添加记账项目
async function addBillType(event) {
	let result = {
		a: true,
		b: {}
	};
	await db.collection(billType).add({
		data: event.data,
		success(res) { //成功打印消息
			console.log(res);
		},
		fail(res) { //存入数据库失败
			throw res;
		}
	})
	return result;
}
// 热度+1
async function billTypeUp(id) {
	await db.collection(billType).doc(id).update({
		// data 传入需要局部更新的数据
		data: {
			// 表示将 o 自增1
			o: _.inc(1)
		},
		success: function(res) {
			console.log(res.data)
		}
	})
}
// 添加记账明细
async function addBill(event) {
	let result = {
		a: true,
		b: {}
	};
	let time = new Date();
	event.d = time.getYear() * 10000 + time.getMonth() * 100 + 100 + time.getDate();
	event.m = time.getYear() * 100 + time.getMonth() + 1;
	event.y = time.getYear();
	event.l = time.toLocaleString();
	event.t = time.getTime();
	await db.collection(dayBill).add({
		data: event,
		success(res) { //成功打印消息
			console.log(res);
		},
		fail(res) { //存入数据库失败
			throw res;
		}
	})
	await billTypeUp(event.billType._id);
	return result;
}

//获取记账明细
async function _getBillList(event) {
	let where = {userInfo:{openId:_.eq(wxContext.OPENID)}};
	if (event.pId === 1 || event === -1) where.billType.pId = _.eq(event.pId);
	if (event.day > 0) where.d = _.eq(event.day);
	if (event.month > 0) where.m = _.eq(event.month);
	if (event.year > 0) where.y = _.eq(event.year);
	if (event.t > -1) where.t = _.gt(event.t);
	let myDb = db.collection(dayBill)
		.where(where)
		.field({
			money: true,
			billType: true,
			l: true,
			t: true
		});
	if (event.orderBy) myDb = myDb.orderBy(event.orderBy, event.des || 'desc');
	if (event.skip) myDb = myDb.skip(event.skip);
	if (event.limit) myDb = myDb.limit(event.limit)
	let result = await myDb.get();
	return result.data;
}
async function getBillList(event) {
	let result = {
		a: true,
		b: {}
	};
	if (!event.orderBy) event.orderBy = 't';
	if (!event.skip) event.skip = 0;
	if (!event.limit) event.limit = 10;
	result.b = await _getBillList(event)
	return result;
}

async function _getTotal(event) {
	let time = new Date();
	let month = event.month || time.getYear() * 100 + time.getMonth() + 1;
	let result = await db.collection(billTotal)
		.where({
			userInfo:{openId:_.eq(wxContext.OPENID)},
			month: _.eq(month)
		})
		.field({
			t: true,
			i:true,
			o:true 
		})
		.limit(1)
		.get();
	return result.data[0];
}
async function _addMonthTotal(event) {
	await db.collection(billTotal).add({
		data: event,
		success(res) {
			console.log(res);
		},
		fail(res) {
			throw res;
		}
	})
}
async function _monthTotalUp(id, i, o, t) {
	await db.collection(billTotal).doc(id).update({
		data: {
			i: _.inc(i),
			o: _.inc(o),
			t: t
		},
		success: function(res) {
			console.log(res.data)
		}
	})
}
async function getMonthTotal(event) {
	let result = {
		a: true,
		b: {}
	};
	let totalData = await _getTotal(event);
	event.t = totalData ? totalData.t : 0;
	result.b = totalData||{};
	let newData = await _getBillList(event);
	if (newData && newData.length > 0) {
		let inTotal = 0;
		let outTotal = 0
		newData.forEach(r => {
			if (r.billType.pId === 1) {
				inTotal += parseFloat(r.money);
			} else {
				outTotal += parseFloat(r.money);
			}
			if (event.t < r.t) event.t = r.t;
		})
		if (totalData) {
			// 更新
			result.b.i = totalData.i + inTotal;
			result.b.o = totalData.o + outTotal;
			await _monthTotalUp(totalData._id, inTotal, outTotal, event.t);
		} else {
			// 插入
			result.b = {
				i: inTotal,
				o: outTotal
			}
			event.i = inTotal;
			event.o = outTotal;
			await _addMonthTotal(event);
		}
	}
	return result;
}
